﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Data;
using System.IO;
using CM = ZofX.NpoiXHelper.Model;

namespace ZofX.NpoiXHelper
{
    /// <summary>
    /// Excel导入类
    /// </summary>
    public class XlsImporter
    {
        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="Code">配置编码</param>
        /// <param name="excelPath">Excel文件路径</param>
        /// <param name="dataRowStartIndex">起始导入序号</param>
        /// <param name="lastDataRowCountIgnore">忽略末尾数据行数</param>
        /// <returns>数据集</returns>
        public static DataSet Import(string Code, string excelPath, int dataRowStartIndex = 0, int lastDataRowCountIgnore = 0)
        {
            //===================获取配置=========================
            CM.Table table = CM.Config.GetXlsImporterConfig(Code);
            Stream xlsStream = new FileStream(excelPath, FileMode.Open, FileAccess.Read);
            return Import(table, xlsStream, dataRowStartIndex, lastDataRowCountIgnore, excelPath.ToLower().EndsWith(".xlsx"));
        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="table">配置表</param>
        /// <param name="excelPath">Excel文件路径</param>
        /// <param name="dataRowStartIndex">起始导入序号</param>
        /// <param name="lastDataRowCountIgnore">忽略末尾数据行数</param>
        /// <returns>数据集</returns>
        public static DataSet Import(CM.Table table, string excelPath, int dataRowStartIndex = 0, int lastDataRowCountIgnore = 0)
        {
            Stream xlsStream = new FileStream(excelPath, FileMode.Open, FileAccess.Read);
            return Import(table, xlsStream, dataRowStartIndex, lastDataRowCountIgnore, excelPath.ToLower().EndsWith(".xlsx"));
        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="Code">配置编码</param>
        /// <param name="excelStream">Excel文件流</param>
        /// <param name="dataRowStartIndex">起始导入序号</param>
        /// <param name="lastDataRowCountIgnore">忽略末尾数据行数</param>
        /// <param name="xlsx">是否XLSX后缀</param>
        /// <returns>数据集</returns>
        public static DataSet Import(string Code, Stream excelStream, int dataRowStartIndex = 0, int lastDataRowCountIgnore = 0, bool xlsx = false)
        {
            //===================获取配置=========================
            CM.Table table = CM.Config.GetXlsImporterConfig(Code);
            return Import(table, excelStream, dataRowStartIndex, lastDataRowCountIgnore, xlsx);
        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="table">配置表</param>
        /// <param name="excelStream">Excel文件流</param>
        /// <param name="dataRowStartIndex">起始导入序号</param>
        /// <param name="lastDataRowCountIgnore">忽略末尾数据行数</param>
        /// <param name="xlsx">是否XLSX后缀</param>
        /// <returns>数据集</returns>
        public static DataSet Import(CM.Table table, Stream excelStream, int dataRowStartIndex = 0, int lastDataRowCountIgnore = 0, bool xlsx = false)
        {
            //===================获取配置=========================
            table.Columns.Sort((c1, c2) =>
            {
                return c1.Order - c2.Order;
            });
            //====================================================

            excelStream.Position = 0;
            IWorkbook workbook = null;
            if (xlsx)
            {
                workbook = new XSSFWorkbook(excelStream);
            }
            else
            {
                workbook = new HSSFWorkbook(excelStream);
            }
            excelStream.Close();
            excelStream.Dispose();

            DataSet ds = new DataSet();
            for (int index = 0; index < workbook.NumberOfSheets; index++)
            {
                DataTable dt = new DataTable();
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    CM.Column tc = table.Columns.Find((c) =>
                    {
                        return c.Code == j.ToString();
                    });
                    if (null != tc)
                    {
                        dt.Columns.Add(tc.Property);
                    }
                }

                ISheet sheet = workbook.GetSheetAt(index);
                System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
                int num = 0;
                while (rows.MoveNext())
                {
                    if (num++ < dataRowStartIndex) continue;

                    IRow row = (IRow)rows.Current;
                    DataRow dr = dt.NewRow();
                    for (int i = 0; i < row.LastCellNum; i++)
                    {
                        ICell cell = row.GetCell(i);

                        CM.Column tc = table.Columns.Find((c) =>
                        {
                            return c.Code == i.ToString();
                        });
                        if (null != tc && null != cell)
                        {
                            dr[tc.Property] = cell.ToString();
                        }
                    }
                    dt.Rows.Add(dr);
                }

                for (var seq = 0; seq < lastDataRowCountIgnore; seq++)
                {
                    dt.Rows.RemoveAt(dt.Rows.Count - 1);
                }
                ds.Tables.Add(dt);
            }
            return ds;
        }
    }
}